package com.youxin.busfoundation.common.es;

import java.util.ArrayList;
import java.util.List;

import com.youxin.busfoundation.common.es.bean.PortraitContactBean;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import com.youxin.busfoundation.common.GlobalConfig;
import com.youxin.busfoundation.common.es.bean.ContactBean;
import com.youxin.busfoundation.common.es.bean.RequestContactBean;
import com.youxin.busfoundation.config.EsConfig;
import com.youxin.busfoundation.utils.es.EsBasePage;
import com.youxin.foundation.interfaces.Convert;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.JsonUtils;

/**
 * @desc 搜索联系人信息
 * @author yingde.cao
 * @update 2017-12-25
 */
public class SearchContact<T> extends BaseSearch<T>{

	@SuppressWarnings("unchecked")
	public SearchContact(Convert<T> convert) {
		super(convert);
	}
	
	public SearchContact() {}
	
	public EsBasePage<Object> queryList(RequestContactBean requestLeadsBean,Class<T> t) throws Exception {		
		try {
			TermQueryBuilder queryBuilder=QueryBuilders.termQuery("company_uid", requestLeadsBean.getCompanyUid());
			return queryList(requestLeadsBean, t, queryBuilder, (srb)->{			
			}
			, new String[] {EsConfig.getConfig().getContactname()},null);
		} catch (Exception e) {
			throw e;
		} finally {
		}
	}

	/**
	 * @description 
	 * @param uids
	 * @return
	 * @throws Exception
	 */
	public List<ContactBean> queryContactInfos(List<String> uids) throws Exception {
		Client client = EsClient.instance().getClient();
		try {
			SearchRequestBuilder srb = client.prepareSearch(EsConfig.getConfig().getContactname());
			srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			.setFrom(0).setSize(1000)
			.setExplain(true);
			String[] terms=uids.toArray(new String[]{});
			srb.setQuery(QueryBuilders.termsQuery("company_uid", terms));
			SearchResponse response = srb.execute().actionGet(GlobalConfig.ES_SEARCH_TIMEOUT);
			SearchHits hits = response.getHits();
			List<ContactBean> list = new ArrayList<>(20);
			for (SearchHit item : hits) {
				String sourceString = item.getSourceAsString();
				ContactBean bean = JsonUtils.stringToFasterxmlObject(sourceString, ContactBean.class);
				if (bean == null) {
					throw new BaseException("数据转换错误");
				}
				list.add(bean);
			}
			return list;
		} catch (Exception e) {
			throw e;
		} finally {
		}
	}
	
	public List<? extends Bucket> queryContactCount(List<String> uids) throws Exception {
		Client client = EsClient.instance().getClient();
		try {
			SearchRequestBuilder srb = client.prepareSearch(EsConfig.getConfig().getContactname());
			srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			//.setFrom(0)
			.setSize(0)
			.setExplain(true);
			String[] terms=uids.toArray(new String[]{});
			srb.setQuery(QueryBuilders.termsQuery("company_uid", terms));
			
			TermsAggregationBuilder teamAgg= AggregationBuilders.terms("contact_count").field("company_uid").size(uids.size()+1);
			srb.addAggregation(teamAgg);
			
			SearchResponse response = srb.execute().actionGet(GlobalConfig.ES_SEARCH_TIMEOUT);
			Aggregations aggreg=response.getAggregations();
			Terms terms2=aggreg.get("contact_count");
			List<? extends Bucket> buckets=terms2.getBuckets();
			return buckets;
		} catch (Exception e) {
			throw e;
		} finally {
		}
	}

	/**
	 * @desc 查询ES联系人 PortraitContactBean.class
	 * @author Kris.wang
	 * @date 2017-12-01
	 * @param requestBean
	 * @return 
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<PortraitContactBean> queryContact(RequestContactBean requestBean, Class<T> cls) throws Exception {
		Client client = EsClient.instance().getClient();
		try {
			SearchRequestBuilder srb = client.prepareSearch(EsConfig.getConfig().getContactname());
			srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
					.setFrom(0).setSize(100)
					.setExplain(true);
			srb.setQuery(QueryBuilders.termQuery("company_uid", requestBean.getCompanyUid()));
			SearchResponse response = srb.execute().actionGet(GlobalConfig.ES_SEARCH_TIMEOUT);
			SearchHits hits = response.getHits();
			List<PortraitContactBean> list = new ArrayList<>(20);
			for (SearchHit item : hits) {
				String sourceString = item.getSourceAsString();
				PortraitContactBean bean = JsonUtils.stringToFasterxmlObject(sourceString, PortraitContactBean.class);
				if (bean == null) {
					throw new BaseException("数据转换错误");
				}
				list.add(bean);
			}
			return list;
		} catch (Exception e) {
			throw e;
		} finally {

		}
	}

}
